package com.heima.search.service.Impl;

import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {


    @Autowired
    BehaviorFeign behaviorFeign;

    @Autowired
    MongoTemplate mongoTemplate;


    /**
     * 删除搜索历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //参数校验
        if (dto == null || dto.getHistoryId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //获取更新后的搜索记录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //删除
        ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (behaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        mongoTemplate.remove(Query.query(Criteria
                        .where("id").is(dto.getHistoryId())
                        .and("entryId").is(behaviorEntry.getId()))
                , ApUserSearch.class);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询搜索历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDto dto) {
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //获取登录信息  查询实体
        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null) {
            ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
            if (behaviorEntry != null) {
                List<ApUserSearch> searchList = mongoTemplate.find(Query.query(Criteria
                                .where("entryId").is(behaviorEntry.getId()))
                                .with(Sort.by(Sort.Order.desc("createdTime")))
                        , ApUserSearch.class);

                return ResponseResult.okResult(searchList);
            }

        }


        return ResponseResult.okResult(new ArrayList<>());
    }

    /**
     * 保存用户搜索历史记录
     *
     * @param dto
     */
    @Override
    @Async  //异步调用
    public void insert(UserSearchDto dto) {
        //参数校验
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            log.info("dto is null");
            return;
        }

        //获取登录信息
        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null) {
            //查询行为实体
            ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
            if (behaviorEntry != null) {
                //查询当前用户的历史记录
                List<ApUserSearch> searchList = mongoTemplate.find(Query.query(Criteria
                                .where("entryId").is(behaviorEntry.getId()))
                                .with(Sort.by(Sort.Order.desc("createdTime")))
                        , ApUserSearch.class);

                ApUserSearch apUserSearch = new ApUserSearch();
                apUserSearch.setCreatedTime(new Date());
                apUserSearch.setEntryId(behaviorEntry.getId());
                apUserSearch.setKeyword(dto.getSearchWords());

                //无历史记录
                if (searchList == null || searchList.size() == 0) {
                    mongoTemplate.save(apUserSearch);
                    return;
                }


                //存在历史记录
                for (ApUserSearch userSearch : searchList) {
                    //存在   更新时间
                    if (userSearch.getKeyword().equals(dto.getSearchWords())) {
                        userSearch.setCreatedTime(new Date());
                        mongoTemplate.save(userSearch);
                        return;
                    }
                }
                //不存在  判断历史记录是否超过十条
                if (searchList.size() < 10) {
                    mongoTemplate.save(apUserSearch);
                } else {
                    ApUserSearch lastSearch = searchList.get(searchList.size() - 1);

                    mongoTemplate.findAndReplace(Query.query(Criteria
                                    .where("id").is(lastSearch.getId()))
                            , apUserSearch);
                }
            }
        }
    }
}
